package com.example;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.scene.layout.HBox;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Optional;

public class AdminDepartmentManagementController {
    // 院系管理相关控件
    @FXML private TableView<Department> departmentTableView;
    @FXML private TableColumn<Department, Integer> departmentIdColumn;
    @FXML private TableColumn<Department, String> departmentNameColumn;
    @FXML private TableColumn<Department, String> departmentDescriptionColumn;
    @FXML private TableColumn<Department, Void> departmentActionColumn;

    // 专业管理相关控件
    @FXML private ComboBox<Department> departmentComboBox;
    @FXML private TableView<Major> majorTableView;
    @FXML private TableColumn<Major, Integer> majorIdColumn;
    @FXML private TableColumn<Major, String> majorNameColumn;
    @FXML private TableColumn<Major, String> majorDepartmentColumn;
    @FXML private TableColumn<Major, String> majorDescriptionColumn;
    @FXML private TableColumn<Major, Void> majorActionColumn;

    // 班级管理相关控件
    @FXML private ComboBox<Department> classDepartmentComboBox;
    @FXML private ComboBox<Major> majorComboBox;
    @FXML private TableView<Class> classTableView;
    @FXML private TableColumn<Class, Integer> classIdColumn;
    @FXML private TableColumn<Class, String> classNameColumn;
    @FXML private TableColumn<Class, String> classMajorColumn;
    @FXML private TableColumn<Class, String> classGradeColumn;
    @FXML private TableColumn<Class, Void> classActionColumn;

    // 数据访问对象
    private DepartmentDAO departmentDAO = new DepartmentDAO();
    private MajorDAO majorDAO = new MajorDAO();
    private ClassDAO classDAO = new ClassDAO();

    // 数据列表
    private ObservableList<Department> departmentList = FXCollections.observableArrayList();
    private ObservableList<Major> majorList = FXCollections.observableArrayList();
    private ObservableList<Class> classList = FXCollections.observableArrayList();

    @FXML
    public void initialize() {
        // 初始化院系表格
        departmentIdColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        departmentNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        departmentDescriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
        departmentActionColumn.setCellFactory(createDepartmentActionButtonCellFactory());

        // 初始化专业表格
        majorIdColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        majorNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        majorDepartmentColumn.setCellValueFactory(new PropertyValueFactory<>("departmentId"));
        majorDescriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
        majorActionColumn.setCellFactory(createMajorActionButtonCellFactory());

        // 初始化班级表格
        classIdColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        classNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        classMajorColumn.setCellValueFactory(new PropertyValueFactory<>("majorId"));
        classGradeColumn.setCellValueFactory(new PropertyValueFactory<>("grade"));
        classActionColumn.setCellFactory(createClassActionButtonCellFactory());

        // 设置表格数据
        departmentTableView.setItems(departmentList);
        majorTableView.setItems(majorList);
        classTableView.setItems(classList);

        // 初始化院系下拉框
        departmentComboBox.setItems(departmentList);
        classDepartmentComboBox.setItems(departmentList);

        // 添加院系选择监听器
        departmentComboBox.setOnAction(e -> loadMajorsByDepartment());
        classDepartmentComboBox.setOnAction(e -> loadMajorsByDepartment());
        majorComboBox.setOnAction(e -> loadClassesByMajor());

        // 加载初始数据
        loadDepartments();
    }

    private void loadDepartments() {
        try {
            departmentList.clear();
            departmentList.addAll(departmentDAO.getAllDepartments());
        } catch (SQLException e) {
            showError("加载院系数据失败：" + e.getMessage());
        }
    }

    private void loadMajorsByDepartment() {
        Department selectedDepartment = departmentComboBox.getValue();
        if (selectedDepartment != null) {
            try {
                majorList.clear();
                majorList.addAll(majorDAO.getMajorsByDepartment(selectedDepartment.getId()));
            } catch (SQLException e) {
                showError("加载专业数据失败：" + e.getMessage());
            }
        }
    }

    private void loadClassesByMajor() {
        Major selectedMajor = majorComboBox.getValue();
        if (selectedMajor != null) {
            try {
                classList.clear();
                classList.addAll(classDAO.getClassesByMajor(selectedMajor.getId()));
            } catch (SQLException e) {
                showError("加载班级数据失败：" + e.getMessage());
            }
        }
    }

    @FXML
    private void handleAddDepartment() {
        showDepartmentDialog(null);
    }

    @FXML
    private void handleAddMajor() {
        if (departmentComboBox.getValue() == null) {
            showError("请先选择院系");
            return;
        }
        showMajorDialog(null);
    }

    @FXML
    private void handleAddClass() {
        if (majorComboBox.getValue() == null) {
            showError("请先选择专业");
            return;
        }
        showClassDialog(null);
    }

    private void showDepartmentDialog(Department department) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("DepartmentDialog.fxml"));
            Parent root = loader.load();
            DepartmentDialogController controller = loader.getController();

            Stage dialogStage = new Stage();
            dialogStage.setTitle(department == null ? "添加院系" : "编辑院系");
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            dialogStage.setScene(new Scene(root));

            controller.setDialogStage(dialogStage);
            controller.setDepartment(department);

            dialogStage.showAndWait();

            if (controller.isConfirmed()) {
                Department updatedDepartment = controller.getDepartment();
                if (department == null) {
                    departmentDAO.addDepartment(updatedDepartment);
                } else {
                    departmentDAO.updateDepartment(updatedDepartment);
                }
                loadDepartments();
            }
        } catch (IOException e) {
            showError("打开院系对话框失败：" + e.getMessage());
        } catch (SQLException e) {
            showError("保存院系数据失败：" + e.getMessage());
        }
    }

    private void showMajorDialog(Major major) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("MajorDialog.fxml"));
            Parent root = loader.load();
            MajorDialogController controller = loader.getController();

            Stage dialogStage = new Stage();
            dialogStage.setTitle(major == null ? "添加专业" : "编辑专业");
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            dialogStage.setScene(new Scene(root));

            controller.setDialogStage(dialogStage);
            controller.setMajor(major);
            controller.setDepartment(departmentComboBox.getValue());

            dialogStage.showAndWait();

            if (controller.isConfirmed()) {
                Major updatedMajor = controller.getMajor();
                if (major == null) {
                    majorDAO.addMajor(updatedMajor);
                } else {
                    majorDAO.updateMajor(updatedMajor);
                }
                loadMajorsByDepartment();
            }
        } catch (IOException e) {
            showError("打开专业对话框失败：" + e.getMessage());
        } catch (SQLException e) {
            showError("保存专业数据失败：" + e.getMessage());
        }
    }

    private void showClassDialog(Class class_) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("ClassDialog.fxml"));
            Parent root = loader.load();
            ClassDialogController controller = loader.getController();

            Stage dialogStage = new Stage();
            dialogStage.setTitle(class_ == null ? "添加班级" : "编辑班级");
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            dialogStage.setScene(new Scene(root));

            controller.setDialogStage(dialogStage);
            controller.setClass(class_);
            controller.setMajor(majorComboBox.getValue());

            dialogStage.showAndWait();

            if (controller.isConfirmed()) {
                Class updatedClass = controller.getClass_();
                if (class_ == null) {
                    classDAO.addClass(updatedClass);
                } else {
                    classDAO.updateClass(updatedClass);
                }
                loadClassesByMajor();
            }
        } catch (IOException e) {
            showError("打开班级对话框失败：" + e.getMessage());
        } catch (SQLException e) {
            showError("保存班级数据失败：" + e.getMessage());
        }
    }

    private Callback<TableColumn<Department, Void>, TableCell<Department, Void>> createDepartmentActionButtonCellFactory() {
        return new Callback<>() {
            @Override
            public TableCell<Department, Void> call(TableColumn<Department, Void> param) {
                return new TableCell<>() {
                    private final Button editButton = new Button("编辑");
                    private final Button deleteButton = new Button("删除");
                    private final HBox buttons = new HBox(5, editButton, deleteButton);

                    {
                        editButton.setOnAction(event -> {
                            Department item = getTableView().getItems().get(getIndex());
                            showDepartmentDialog(item);
                        });
                        deleteButton.setOnAction(event -> {
                            Department item = getTableView().getItems().get(getIndex());
                            handleDelete("department", item);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        setGraphic(empty ? null : buttons);
                    }
                };
            }
        };
    }

    private Callback<TableColumn<Major, Void>, TableCell<Major, Void>> createMajorActionButtonCellFactory() {
        return new Callback<>() {
            @Override
            public TableCell<Major, Void> call(TableColumn<Major, Void> param) {
                return new TableCell<>() {
                    private final Button editButton = new Button("编辑");
                    private final Button deleteButton = new Button("删除");
                    private final HBox buttons = new HBox(5, editButton, deleteButton);

                    {
                        editButton.setOnAction(event -> {
                            Major item = getTableView().getItems().get(getIndex());
                            showMajorDialog(item);
                        });
                        deleteButton.setOnAction(event -> {
                            Major item = getTableView().getItems().get(getIndex());
                            handleDelete("major", item);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        setGraphic(empty ? null : buttons);
                    }
                };
            }
        };
    }

    private Callback<TableColumn<Class, Void>, TableCell<Class, Void>> createClassActionButtonCellFactory() {
        return new Callback<>() {
            @Override
            public TableCell<Class, Void> call(TableColumn<Class, Void> param) {
                return new TableCell<>() {
                    private final Button editButton = new Button("编辑");
                    private final Button deleteButton = new Button("删除");
                    private final HBox buttons = new HBox(5, editButton, deleteButton);

                    {
                        editButton.setOnAction(event -> {
                            Class item = getTableView().getItems().get(getIndex());
                            showClassDialog(item);
                        });
                        deleteButton.setOnAction(event -> {
                            Class item = getTableView().getItems().get(getIndex());
                            handleDelete("class", item);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        setGraphic(empty ? null : buttons);
                    }
                };
            }
        };
    }

    private void handleDelete(String type, Object item) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("删除" + (type.equals("department") ? "院系" : type.equals("major") ? "专业" : "班级"));
        alert.setContentText("确定要删除吗？");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            try {
                switch (type) {
                    case "department":
                        departmentDAO.deleteDepartment(((Department) item).getId());
                        loadDepartments();
                        break;
                    case "major":
                        majorDAO.deleteMajor(((Major) item).getId());
                        loadMajorsByDepartment();
                        break;
                    case "class":
                        classDAO.deleteClass(((Class) item).getId());
                        loadClassesByMajor();
                        break;
                }
            } catch (SQLException e) {
                showError("删除失败：" + e.getMessage());
            }
        }
    }

    private void showError(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
} 